﻿using System;
using System.Windows.Input;

namespace vBridge.Design.Mvvm.Command
{
    /// <summary>
    /// A command whose sole purpose is to relay its functionality to other objects by invoking delegates. The default return value for the CanExecute method is 'true'.
    /// </summary>
    public class RelayCommand : ICommand
    {
        private readonly Action _action;
        private readonly Func<Boolean> _predicate;

        /// <summary>
        /// Initializes a new instance of the <see cref="RelayCommand"/> class.
        /// </summary>
        /// <param name="action">The action that will be taken.</param>
        /// <param name="predicate">The predicate that will allow or disallow the invocation of the action.</param>
        public RelayCommand(Action action, Func<Boolean> predicate)
        {
            _action = action;
            _predicate = predicate;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="RelayCommand"/> class.
        /// </summary>
        /// <param name="action">The action that will be taken.</param>
        public RelayCommand(Action action)
            : this(action, () => true)
        {
        }

        public event EventHandler CanExecuteChanged;

        public Boolean CanExecute(Object parameter)
        {
            return _predicate();
        }

        public virtual void Execute(Object parameter)
        {
            _action();
        }
    }
}